package com.afeng.util.common;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * 
 * @Title       : IpUtil
 * @Description : IP工具类
 * @Date        : 2017年11月16日
 * @author      : afeng
 */
public class IpUtil {

    /**
     * 把服务器本机ip地址转换为long数字
     */
    public static long getLocalIp2Long() {
        List<String> ipList = getLocalIpList();
        String ipAddr = "127.0.0.1";
        if (ipList == null || ipList.size() == 0) {
            return ip2Long(ipAddr);
        }
        for (String ip : ipList) {
            if (ip.equals(ipAddr)) {
                continue;
            } else {
                ipAddr = ip;
                break;
            }
        }
        return ip2Long(ipAddr);
    }
    
    /**
     * ip转换为long类型数字
     */
    public static long ip2Long(String ip) {
        long ret = 0;
        String ipGroups[] = ip.split("\\.");
        Long[] ipLong = new Long[4];
        for (int i = 0; i < ipGroups.length; i++) {
            ipLong[i] = Long.valueOf(ipGroups[i]);
        }
        /*
         * 1、左移运算符，移动一位，相当于乘以2，ip每个段最大256，所以每个段按照8位二进制即可
         * 2、对每个段的二进制进行或运算，获取一个long类型的ip
         */
        ret = ipLong[0] << 24 | ipLong[1] << 16 | ipLong[2] << 8 | ipLong[3];
        return ret;
    }
    
    /**
     * 获取本机ip列表
     */
    public static List<String> getLocalIpList() {
        List<String> ipList = new ArrayList<String>();
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            NetworkInterface networkInterface;
            Enumeration<InetAddress> inetAddresses;
            InetAddress inetAddress;
            String ip;
            while (networkInterfaces.hasMoreElements()) {
                networkInterface = networkInterfaces.nextElement();
                inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    inetAddress = inetAddresses.nextElement();
                    if (inetAddress != null && inetAddress instanceof Inet4Address) { // IPV4
                        ip = inetAddress.getHostAddress();
                        ipList.add(ip);
                    }
                }
            }
        } catch (SocketException e) {
        }
        return ipList;
    }

}
